<template>
<div>
    <el-dialog
        title="添加用户"
        @close="addDialogClosed"
        v-model="dialogFormVisible"
    >
        <el-form
            label-width="100px"
            style="max-width: 460px"
            :rules="rules"
            :model="addItem"
            ref="addUserref"
        >
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addItem.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addItem.password" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addItem.email" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="emit('addUsercancel')">取消</el-button>
                <el-button type="primary" @click="define">确定</el-button>
            </span>
        </template>
    </el-dialog>
</div>
</template>

<script setup>
    import { ElMessage } from 'element-plus'
    import { reactive } from 'vue-demi'
    import request from '@/utils/request.js'
    import { ref } from 'vue'
    import { defineProps } from 'vue'

    let props = defineProps({
        dialogFormVisible:{
            type: Boolean,
            default:false,
        }
    })

    

    const addUserref = ref(null)
    const rules = {
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            {
                min: 3,
                max: 10,
                message: '长度在 3 到 10 个字符',
                trigger: 'blur',
            },
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            {
                min: 6,
                max: 15,
                message: '长度在 6 到 15 个字符',
                trigger: 'blur',
            },
        ],
        email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {
                pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
                message: '邮箱格式不正确',
                trigger: 'blur',
            },
        ],
    }

    const addItem = reactive({
        username:'',
        password:'',
        email:'',
    })
   

    const emit = defineEmits(['addUsercancel'])
   
    const define = function(){
        addUserref.value.validate(async function(valid){
            if(!valid) return
            const {data} = await request.put('/user/add',{...addItem})
            emit('addUsercancel')

            if(data.code === 200){
                ElMessage.success('添加用户成功')
            }
        })
    }

    
    const addDialogClosed = function(){
        addUserref.value.resetFields()
    }


        

</script>

<style>

</style>